package edu.whu.rose.clock.ssql.index;

import java.io.UnsupportedEncodingException;

import com.sleepycat.je.Cursor;
import com.sleepycat.je.Database;
import com.sleepycat.je.DatabaseConfig;
import com.sleepycat.je.DatabaseEntry;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.Environment;
import com.sleepycat.je.LockMode;
import com.sleepycat.je.OperationStatus;

public class IndexDB {

	private final Environment dbEnv;
	private final String dbName;
	private Database db;
	
	public IndexDB(Environment dbEnv, String dbName) {
		this.dbEnv = dbEnv;
		this.dbName = dbName;
	}
	
	public boolean openDB() {
		try {
			DatabaseConfig dbConfig = new DatabaseConfig();
			dbConfig.setAllowCreate(true);
			this.db = dbEnv.openDatabase(null, dbName, dbConfig);
			return true;
		}
		catch (DatabaseException ex) {
			ex.printStackTrace();
			System.err.println("Error: opening index database \"" + dbName + "\"");
			return false;
		}
	}
	
	public void closeDB() {
		try {
			if (db != null) {
				db.close();
			}
		}
		catch (DatabaseException ex) {
			ex.printStackTrace();
			System.err.println("Error: closing index database \"" + dbName + "\"");
		}
	}
	
	public void put(DatabaseEntry key, DatabaseEntry value) throws DatabaseException {
		db.put(null, key, value);
	}
	
	public void put(String key, String value) throws UnsupportedEncodingException, DatabaseException {
		DatabaseEntry keyword = new DatabaseEntry(key.getBytes("UTF-8"));
		DatabaseEntry list = new DatabaseEntry(value.getBytes("UTF-8"));
		db.put(null, keyword, list);
	}
	
	public DatabaseEntry get(DatabaseEntry keyword) throws DatabaseException {
		DatabaseEntry list = new DatabaseEntry();
		if (db.get(null, keyword, list, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
			return list;
		}
		else {
			return null;
		}
	}
	
	public String get(String key) throws UnsupportedEncodingException, DatabaseException {
		DatabaseEntry keyword = new DatabaseEntry(key.getBytes("UTF-8"));
		DatabaseEntry list = new DatabaseEntry();
		if (db.get(null, keyword, list, LockMode.DEFAULT) == OperationStatus.SUCCESS) {
			return new String(list.getData(), "UTF-8");
		}
		else {
			return null;
		}
	}

	public Database getDB() {
		return db;
	}
	
	public Cursor getCursor() throws DatabaseException {
		return db.openCursor(null, null);
	}

}
